"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Skeleton } from "@/components/ui/skeleton"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { AlertCircle, WifiOff } from "lucide-react"
import { getActivePolls } from "@/lib/db"

interface PollOption {
  id: string
  poll_id: string
  text: string
  votes: number
}

interface Poll {
  id: string
  title: string
  description: string
  active: boolean
  created_at: string
  options?: PollOption[] // 使用 options 而不是 poll_options
  poll_options?: PollOption[] // 保留 poll_options 以兼容旧数据
}

export default function ActivePolls() {
  const [polls, setPolls] = useState<Poll[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [isOffline, setIsOffline] = useState(false)
  const [votedPolls, setVotedPolls] = useState<string[]>([])

  useEffect(() => {
    // 监听网络状态
    const handleOnline = () => setIsOffline(false)
    const handleOffline = () => setIsOffline(true)

    window.addEventListener("online", handleOnline)
    window.addEventListener("offline", handleOffline)

    // 初始化网络状态
    setIsOffline(!navigator.onLine)

    return () => {
      window.removeEventListener("online", handleOnline)
      window.removeEventListener("offline", handleOffline)
    }
  }, [])

  useEffect(() => {
    const fetchPolls = async () => {
      try {
        setLoading(true)
        setError(null)

        const data = await getActivePolls()
        console.log("Fetched polls:", data) // 添加日志，帮助调试
        setPolls(data)
        
        // 获取用户已投票的列表
        const storedVotedPolls = JSON.parse(localStorage.getItem("votedPolls") || "[]")
        setVotedPolls(storedVotedPolls)
      } catch (error) {
        console.error("Error fetching polls:", error)
        setError("无法加载投票数据，请稍后再试")
      } finally {
        setLoading(false)
      }
    }

    fetchPolls()
  }, [])

  if (loading) {
    return (
      <div className="space-y-4">
        {[1, 2, 3].map((i) => (
          <Card key={i}>
            <CardHeader>
              <Skeleton className="h-6 w-3/4" />
              <Skeleton className="h-4 w-1/2 mt-2" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-4 w-full mt-2" />
            </CardContent>
            <CardFooter>
              <Skeleton className="h-10 w-24" />
            </CardFooter>
          </Card>
        ))}
      </div>
    )
  }

  if (isOffline) {
    return (
      <Alert className="mb-4">
        <WifiOff className="h-4 w-4" />
        <AlertDescription>
          您当前处于离线状态。显示的数据可能不是最新的。
          {polls.length > 0 && " 但您仍然可以查看缓存的投票。"}
        </AlertDescription>
      </Alert>
    )
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertDescription>{error}</AlertDescription>
      </Alert>
    )
  }

  if (polls.length === 0) {
    return (
      <div className="text-center py-8">
        <p className="text-gray-500">目前没有活跃的投票</p>
        <p className="text-sm text-gray-400 mt-2">请管理员创建新的投票</p>
      </div>
    )
  }

  return (
    <div className="space-y-2 sm:space-y-3 md:space-y-4">
      {polls.map((poll) => {
        // 获取选项数组，兼容 options 和 poll_options
        const options = poll.options || poll.poll_options || []

        // 计算总票数，添加空值检查
        const totalVotes = options ? options.reduce((sum, option) => sum + (option.votes || 0), 0) : 0
        
        // 检查用户是否已投票
        const hasVoted = votedPolls.includes(poll.id)
        
        // 处理标题和描述的显示
        const displayTitle = hasVoted ? 
          (poll.title && poll.title.length > 16 ? poll.title.substring(0, 16) + "......" : poll.title || "") : 
          (poll.title || "")
          
        const displayDescription = hasVoted ? 
          (poll.description && poll.description.length > 16 ? poll.description.substring(0, 16) + "......" : poll.description || "") : 
          (poll.description || "")

        return (
          <Card key={poll.id}>
            <CardHeader>
              <div className="flex justify-between items-start">
                <CardTitle>{displayTitle}</CardTitle>
                {hasVoted ? 
                  <Badge className="bg-blue-500/50">已投票</Badge> : 
                  (poll.active ? <Badge className="bg-green-500/50">进行中</Badge> : <Badge variant="outline" className="opacity-50">已结束</Badge>)}
              </div>
              <CardDescription>{displayDescription}</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="text-sm text-gray-500">已有 {totalVotes} 人参与投票</div>
            </CardContent>
            <CardFooter>
              <Link href={`/poll/${poll.id}`} passHref>
                <Button>{hasVoted ? "查看" : "参与投票"}</Button>
              </Link>
            </CardFooter>
          </Card>
        )
      })}
    </div>
  )
}
